package com.hjx.demo.client;

import com.hjx.rw.Loops;
import com.hjx.rw.SlidingWindowCounter;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by houjinxin on 2017/3/11.
 */
public class DemoClient {

    private static final Logger logger = LoggerFactory.getLogger(DemoClient.class);

    public static int get(String uri){
        CloseableHttpClient httpclient = HttpClients.custom()
//                .setProxy(new HttpHost("127.0.0.1", 8888))
                .build();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(60000)
                .setSocketTimeout(60000)
                .build();

        HttpHead httpHead = new HttpHead(uri);
        httpHead.setConfig(requestConfig);

        CloseableHttpResponse response;
        try {
            response = httpclient.execute(httpHead);
            System.out.println("状态行：" + response.getStatusLine());
            return response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            logger.error("异常描述",e);
            e.printStackTrace();
        }
        return 0;
    }

    public static long getResponseTime(String uri, SlidingWindowCounter passCount, SlidingWindowCounter noPassCount) throws InterruptedException {
//        Thread.sleep(2000);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setProxy(new HttpHost("127.0.0.1", 8888))
                .build();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(60000)
                .setSocketTimeout(60000)
                .build();

        HttpHead httpHead = new HttpHead(uri);
        httpHead.setConfig(requestConfig);

        CloseableHttpResponse response;
        try {
            long start = System.currentTimeMillis();
            httpclient.execute(httpHead);
            long end = System.currentTimeMillis();
            long times = end - start;
            if (times > 100) {
                Loops.increase(passCount::increase);
            } else {
                Loops.increase(noPassCount::increase);
            }
            return times;
        } catch (Exception e) {
            logger.error("异常描述",e);
            e.printStackTrace();
        }
        return 0;
    }
}
